# coding: utf-8

from decimal import Decimal
from sqlalchemy import cast, DECIMAL

from app.products.constant import scene_to_waterproof, CalculateItem, TypeToName
from app.products.models import ProductTemplate, ProductToParam


class ProductOptions(object):
    """
    create by ld_wu 2017-08-24
    产品下拉框基类
    """

    def __init__(self, source):
        # 像素间距
        self.spacing = source.get('spacing')
        # 户内外
        self.scene_type = source.get('scene_type', type=int)
        # 颜色
        self.color = source.get('color', type=int)
        # 传输方式
        self.transport = source.get('transport', type=int)
        # 是否防水
        self.waterproof = scene_to_waterproof.get(self.scene_type)
        # 产品类型id
        self.product_type_id = source.get('product_type_id', type=int)
        # 产品常量对应id
        self.type_id = source.get('type_id', type=int)

    def option_values(self):
        query = ProductTemplate.query.filter(
            ProductTemplate.product_type_id == self.product_type_id
        ).with_entities(
            ProductTemplate.id.label('product_id'),
            ProductTemplate.name.label('product_name'),
            ProductTemplate.brand.label('brand'),
            ProductTemplate.suggest_price.label('suggest_price')
        )
        query = self.extra_filter(query)
        return query.all()

    def extra_filter(self, query):
        if self.type_id in [TypeToName.MODULE_GROUP, TypeToName.ORIGINAL_BOX]:
            # 户内/户外
            if self.scene_type:
                query = query.filter(
                    ProductTemplate.scene == self.scene_type
                )
            # 全彩/单色/双色
            if self.color:
                query = query.filter(ProductTemplate.color == self.color)

            # 是否防水
            if self.waterproof:
                query = query.filter(ProductTemplate.waterproof == self.waterproof)
        if self.type_id == TypeToName.MODULE_GROUP:
            if self.spacing:
                query = query.join(
                    ProductToParam, ProductTemplate.id == ProductToParam.product_template_id
                ).filter(
                    ProductToParam.calculate_item == CalculateItem.SPACING,
                    cast(ProductToParam.value, DECIMAL) <= Decimal(self.spacing)
                )

        return query
